package com.heima.search.interceptor;

import com.heima.utils.thread.AppThreadLocalUtil;
import com.heima.utils.thread.WeThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaquanen
 * @version 1.0
 * @project heima-leadnews
 * @date 2024/7/21 16:35:52
 */
@Component
public class SearchInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的userId
        String userId = request.getHeader("userId");
        if(!StringUtils.isEmpty(userId))
        {
            AppThreadLocalUtil.setUserId(Integer.valueOf(userId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
      WeThreadLocalUtil.remove();
    }
}
